<!--
 * @author hemengxia
 创建--红包活动
-->
<template>
  <section class="red-envelope-activity-manage">
    <div class="manage-title">新建/编辑红包活动</div>
    <section class="manage-main">
      <el-form
        ref="form"
        v-loading="formloading"
        :model="form"
        :rules="rules"
        label-width="250px"
        class="main-form"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>

        <el-form-item label="活动起止时间" prop="time">
          <el-date-picker
            v-model="form.time"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            :style="{width:'100%'}"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="封面图" prop="image">
          <image-upload
            :key="uploadImg.imagecropperKey"
            v-model="form.image"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="702"
            :view="uploadImg.view"
            :height="310"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="红包配置" prop="redpacketsActivityId">

          <el-tag v-if="form.redpacketsActivityId" :closable="state=='create'" @close="closeTag()">
            {{ form.title }}
          </el-tag>
          <el-button v-else class="button-new-tag" size="small" @click="showDetail = true">选择红包配置</el-button>
        </el-form-item>
        <el-form-item label="游戏配置" prop="gameManageId">

          <el-tag v-if="form.gameManageId" :closable="state=='create'" @close="closeGameTag()">
            {{ form.gameManageName }}
          </el-tag>
          <el-button v-else class="button-new-tag" size="small" @click="showGamePop = true">选择游戏配置</el-button>
        </el-form-item>

        <el-form-item label="活动说明" prop="activityExplain">
          <el-input
            v-model="form.activityExplain"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6}"
            placeholder="请输入活动说明"
            maxlength="1000"
          />
        </el-form-item>
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px;" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px;" type="primary" @click="handleSubmit">确定</el-button>
    </div>
    <!--  红包配置列表      -->
    <config-list
      v-if="showDetail"
      @cancel="showDetail = false"
      @selectConfig="selectConfig"
    />
    <!--  游戏列表      -->
    <game-list
      v-if="showGamePop"
      @cancel="showGamePop = false"
      @selectGameConfig="selectGameConfig"
    />
  </section>
</template>
<script>

import {
  insert,
  update,
  get
} from '@/views/gameactivity/api/index'
import ConfigList from '@/views/gameactivity/components/configList'
import GameList from '@/views/gameactivity/components/gameList'

export default {
  name: 'GameActivityManage',
  components: { ConfigList, GameList },
  data() {
    return {
      state: 'create',
      formloading: false,
      form: {
        id: '',
        name: '',
        redpacketsActivityId: '', // 红包配置id
        title: '', // 红包配置名称
        image: '',
        time: [],
        activityExplain: '',
        publishStatus: 'RPAPUBSTATUS0',
        gameManageId: '',
        gameManageName: '',
        activityType: 'ACTIVITY02'
      },

      rules: {
        name: [{
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 100,
          message: '长度在 1 到 100 个字符',
          trigger: 'blur'
        }
        ],

        image: [{
          required: true,
          message: '请设置封面图片',
          trigger: 'blur'
        }],
        time: [{
          required: true,
          message: '请选择活动时间',
          trigger: 'blur'
        }],
        activityExplain: [{
          required: true,
          message: '请输入活动说明',
          trigger: 'blur'
        }]

      },
      dict: {
        REDPACT: []
      },
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      showTinymce: false,
      showDetail: false,
      obj: {},
      showGamePop: false
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    }
  },
  methods: {
    /**
     * 选择了红包配置
     * */
    selectConfig(data) {
      this.form.redpacketsActivityId = data.id
      this.form.title = data.title
      this.showDetail = false
    },
    /**
     * 删除选择的红包配置
     * */
    closeTag() {
      this.form.redpacketsActivityId = ''
      this.form.title = ''
    },
    /**
     * 删除选择的游戏配置
     * */
    closeGameTag() {
      this.form.gameManageId = ''
      this.form.gameManageName = ''
    },
    /**
     * 选择了游戏配置
     * */
    selectGameConfig(data) {
      this.form.gameManageId = data.id
      this.form.gameManageName = data.name
      this.showGamePop = false
    },

    formatTime(str) {
      return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
    },

    handleSubmit() {
      this.state === 'create' ? this.createData() : this.updateData()
    },

    handleCancel() {
      this.$router.back()
    },

    /*
     * 新增
     * */
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['activityStartDatetime'] = params.time && params.time.length > 0 ? params.time[0] : ''
          params['activityEndDatetime'] = params.time && params.time.length > 0 ? params.time[1] : ''
          delete params['time']
          return new Promise((resolve, reject) => {
            insert(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1500
              })
              this.$router.back()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    /**
     * 编辑提交
     */
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = {
            ...this.form
          }
          params['activityStartDatetime'] = params.time && params.time.length > 0 ? params.time[0] : ''
          params['activityEndDatetime'] = params.time && params.time.length > 0 ? params.time[1] : ''
          delete params['time']
          return new Promise((resolve, reject) => {
            update(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.$router.back()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    /**
     * 获取详情
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'time') {
              if (data['activityStartDatetime'] && data['activityEndDatetime']) {
                this.form[key] = [data['activityStartDatetime'], data['activityEndDatetime']]
              }
            } else {
              this.form[key] = data[key]
            }
          }
          this.uploadImg.viewId = data.image
          this.showTinymce = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss">

.red-envelope-activity-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px;
      /*对垂直流动条有效*/
      height: 1px;
      /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;

    .line {
      text-align: center;
    }

    .form-card {
      margin-top: 20px;

      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }

    .coupon-num input {
      text-align: left;
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .tip {
      @include font-color($mainColor);
      font-size: 14px;
      padding-left: 250px;
      margin-top: 0;
    }

    .join-conditions-content {
      border: 1px dashed #eee;
      padding: 10px;
      margin-bottom: 20px;

      .title {
        vertical-align: middle;
        font-size: 16px;
        color: #606266;
        line-height: 40px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        margin: 0;
        font-weight: 700;
      }
    }

  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
